package JUC.Lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReenterLock 可重入Demo
 *
 * @author CKC
 * @DateTime 2021/3/31 11:39
 */
public class ReenterLockDemo {
    public static void main(String[] args) {

        Phone phone = new Phone();
        new Thread(phone::sendSMS, "T1").start();
        new Thread(phone::sendSMS, "T2").start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("-------------------------------");
        new Thread(phone, "t3").start();
        new Thread(phone, "t4").start();
    }
}


class Phone implements Runnable {

    Lock lock = new ReentrantLock();

    public synchronized void sendSMS() {
        System.out.println(Thread.currentThread().getName() + "\t method  sendSMS");
        sendEmail();
    }

    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName() + "\t ###method  sendEmail");
    }

    @Override
    public void run() {
        get1();
    }

    public void get1() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t method  get1");
            get2();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void get2() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t -------method  get2");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

